package com.phone.servlet.user;

import com.phone.DBHelper;
import com.phone.entity.Result;
import com.phone.entity.User;
import com.phone.exception.BaseException;
import com.phone.handle.UserHandle;
import com.phone.servlet.BaseServlet;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Package name com.phone.servlet.user
 * Created by tisen
 * On 2017/7/25. in 19:26
 */
public class Password extends BaseServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String phone = request.getParameter("phone");
        String newpassword = request.getParameter("newpassword");
        Session session = DBHelper.getSession();
        session.beginTransaction();
        UserHandle handle = new UserHandle(session);
        Result<User> result = new Result<>();
        result.setObject(null);
        try {
            if (username != null && !username.equals(""))
                result.setObject(handle.password(username, password, newpassword));
            else {
                result.setObject(handle.password(phone, newpassword));
            }
            result.setReason("reset password successful");
            result.setResult(SUCCESS);
            session.getTransaction().commit();
        } catch (HibernateException exception) {
            exception.printStackTrace();
            result.setReason("sql error");
            session.getTransaction().rollback();
        } catch (BaseException exception) {
            exception.printStackTrace();
            result.setReason(exception.getMessage());
            session.getTransaction().rollback();
        } catch (Exception e) {
            result.setReason(e.getMessage());
            e.printStackTrace();
        } finally {
            if (session != null && session.isOpen())
                session.close();
            out(response, result);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
